<template>
  <!--  数据清洗字段管理  -->
  <div class="dictMapping app-container">
    <el-row :gutter="20" class="full-row">
      <!--部门数据-->
      <div class="full-height" style="padding: 20px;">
        <el-input v-model="filterText" prefix-icon="el-icon-search" placeholder="输入关键字进行过滤" maxlength="100" clearable @keyup.enter.native="handleFilter(filterText)" @clear="handleFilter(filterText)" />
        <div class="head-container" style="flex: 1; overflow: auto">
          <div class="title hk-flex" @click="handleFilterAll">
            <div class="tit-left">
              <i :class="showchild ? 'el-icon-arrow-down' : 'el-icon-arrow-right'" />
              <span>类型</span>
            </div>
            <!-- 按钮不可见占位用 -->
            <el-button type="text" icon="el-icon-plus" style="visibility: hidden;" />
          </div>
          <el-tree
            v-show="showchild"
            ref="tree"
            :expand-on-click-node="false"
            default-expand-all
            :data="deptOptions"
            :props="defaultProps"
            current-node-key="1"
            :filter-node-method="filterNode"
            node-key="id"
            :highlight-current="isHightlight"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" style="width: 90%; display: flex">
              <!-- <span>{{ data.itemLabel }}</span> -->
              <span v-if="data.itemLabel.length < 13">{{ data.itemLabel }}</span>
              <el-tooltip v-else class="item" effect="dark" :content="data.itemLabel" placement="top">
                <span
                  style="overflow: hidden;
                  text-overflow:ellipsis;
                  white-space: nowrap;"
                >{{ data.itemLabel }}</span>
              </el-tooltip>
              <!-- <span v-if="!data.showInput" class="custom-tree-node">
                <span>{{ data.itemLabel }}</span>
                <i v-show="data.flag != false">
                  这个按钮要注释
                  <el-button
                    v-if="data.isLeaf == 0"
                    type="text"
                    size="mini"
                    icon="el-icon-plus"
                    @click.stop="() => append(data)" />
                  <el-button type="text" size="mini" icon="el-icon-edit" @click.stop="() => editNode(node, data)" />
                  <el-button type="text" size="mini" icon="el-icon-delete" @click.stop="() => delNode(node, data)" />
                </i>
              </span>
              <span v-else class="custom-tree-node">
                <el-input v-model="data.itemLabel" placeholder="不能为空" size="mini" class="innerput" />
                <i>
                  <el-button type="text" size="mini" @click.stop="() => sureNode(node, data)"> 确定 </el-button>

                  <el-button type="text" size="mini" @click.stop="() => remove(node, data)"> 取消 </el-button>
                </i>
              </span> -->
            </span>
          </el-tree>
        </div>
      </div>
      <!--用户数据-->
      <div class="user">
        <search-form
          :data="queryParams"
          :field-list="filterInfo.fieldList"
          :list-type-info="labelObj"
          @handleSearch="handleQuery"
          @handleReset="resetQuery"
          @handleEvent="handleEvent"
        />
        <el-row :gutter="10" class="mt2">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              :disabled="isLeaf == 1"
              @click="handleAdd"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              size="mini"
              icon="el-icon-delete"
              :disabled="ids.length == 0"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
        </el-row>

        <HkTable
          style="flex: 1; overflow: auto"
          :loading="loading"
          :table-data="tableDataList"
          :table-columns="tableList"
          :selection="true"
          :operate="true"
          :total="total"
          :show-index="true"
          :common-fixed="true"
          :query-params="queryParams"
          :operate-width="250"
          :table-height="80"
          @handleSelectionChange="handleSelectionChange"
          @changePage="getDataList"
        >
          <template #templateType="scope">
            <span
              style="overflow: hidden;
                  text-overflow:ellipsis;
                  white-space: nowrap;"
            >
              {{ (deptOptions.find(item => item.itemVale === scope.row.templateType)).itemLabel }}
            </span>
          </template>
          <template #generateType="scope">
            <span style="width: 100px; display: flex; align-items: center">
              {{ scope.row.generateType == 1 ? '自动' : '手动' }}
            </span>
          </template>
          <template #status="scope">
            <span style="display: flex; align-items: center;">
              <img
                style="width: 20px; margin-right: 10px"
                :src="require(`@/assets/images/zhuangtai${scope.row.status}.png`)"
              >
              {{ scope.row.status == 2 ? '生成成功' : scope.row.status == 0 ? '生成失败' : '生成中' }}
            </span>
          </template>
          <template #operate="scope">
            <div v-if="scope.row.status == 2">
              <el-button size="mini" type="text" @click="handlePreview(scope.row)">预览 </el-button>
              <el-dropdown v-if="scope.row.fileTypes" trigger="click" @command="handleCommand($event, scope.row)">
                <span class="el-dropdown-link"> 下载<i class="el-icon-arrow-down el-icon--right" /> </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-if="scope.row.fileTypes.includes('pdf')" command="pdf">PDF</el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.fileTypes.includes('doc')" command="doc">DOC</el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.fileTypes.includes('wps')" command="wps">WPS</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除 </el-button>
              <el-button
                v-if="scope.row.generateType == 1 && scope.row.configId"
                size="mini"
                type="text"
                @click="handleRelevance(scope.row)"
              >生成配置
              </el-button>
            </div>
            <div v-if="scope.row.status == 0">
              <el-popover placement="top-start" width="200" trigger="hover">
                <div class="msg-title">
                  <img
                    src="@/assets/images/zhuangtai3.png"
                    alt=""
                    style="width: 16px; margin-right: 10px"
                  >报告生成出错，请联系管理员！
                </div>
                <div style="padding: 10px 5px">
                  错误日志如下：<br>
                  {{ scope.row.generateLog }}
                </div>
                <el-button slot="reference" size="mini" type="text">查看日志 </el-button>
              </el-popover>
            </div>
          </template>
        </HkTable>
      </div>
    </el-row>

    <!-- 编辑对话框 -->
    <add-report ref="editRef" :title="title" @handleSubmit="handleSubmit" />
  </div>
</template>

<script>
import SearchForm from '@/components/HkSearchform'
import { queryPageList, deleteReport } from '@/api/reportCenter/safetyReportManagement'
import { getTemplateType, addTemplateType, editTemplateType, delTemplateType } from '@/api/reportCenter/templateManage'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import HkTable from '@/components/Hk-Table/index'
import AddReport from './addReport'

export default {
  name: 'DictMapping',

  components: {
    SearchForm,
    HkTable,
    AddReport
  },
  data() {
    return {
      // 是否是添加状态
      appendState: false,
      // 字典维护所需要的
      upholdId: '',
      dictCode: '',
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 查询
      filterInfo: {
        fieldList: [
          { label: '报告名称', type: 'input', field: 'keyword', maxlength: 100 },
          {
            label: '生成方式',
            type: 'select',
            field: 'generateType',
            list: 'typeList'
          },
          {
            label: '生成时间',
            type: 'dateRange',
            field: 'reportTime'
          },
          { label: '生成状态', type: 'select', field: 'status', list: 'statusList' }
        ]
      },
      labelObj: {
        typeList: [
          { value: 1, label: '自动' },
          { value: 2, label: '手动' }
        ],
        statusList: [
          { value: '0', label: '失败' },
          { value: '1', label: '生成中' },
          { value: '2', label: '成功' }
        ]
      },
      // 总条数
      total: 0,
      // 部门列表
      deptId: '',
      // 右侧新增是否可点击
      isLeaf: '',
      // 部门列表
      deptOptions: [],
      // 字典表格数据
      tableDataList: [],
      // 弹出层标题
      title: '添加',
      // 查询参数
      queryParams: {
        current: 1,
        size: 10
      },
      // 表单参数
      form: {
        type: this.groupType,
        dictKey: undefined,
        dictValue: undefined,
        dictCode: undefined,
        sort: undefined,
        parentId: this.deptId
      },

      //  表格
      tableList: [
        { label: '报告名称', param: 'reportName', width: 260 },
        { label: '类型', param: 'templateType', type: 'slot', width: 160 },
        { label: '报告模板', param: 'templateName', width: 200 },
        { label: '生成方式', param: 'generateType', type: 'slot', width: '100' },
        { label: '报告时间', param: 'reportTime', width: 240 },
        { label: '创建人', param: 'creator', width: 140 },
        { label: '生成时间', param: 'createTime', width: 160 },
        { label: '状态', param: 'status', type: 'slot', width: 120 }
      ],
      defaultProps: {
        children: 'children',
        label: 'dictKey'
      },
      groupType: '1',
      // 是否显示搜索条件
      showchild: true,
      filterText: '',
      //  模板类型
      templateTypeList: [
        { key: '1', label: '保密监管' },
        { key: '2', label: '保密态势' },
        { key: '3', label: '自定义' }
      ],
      isHightlight: false
    }
  },
  watch: {
    groupType(newValue, oldValue) {
      this.getTreeselect()
      this.handleQuery()
    },
    deptId() {}
  },
  created() {
    this.getTreeselect()
    this.handleQuery()
  },

  methods: {
    // 查詢全部
    handleFilterAll() {
      this.isHightlight = false
      // this.showchild = !this.showchild
      this.queryParams.templateType = null
      this.getDataList()
    },
    //  左侧筛选
    handleFilter(val) {
      this.$refs.tree.filter(val)
    },
    // 增加树节点
    append(data) {
      this.appendState = true
      const newChild = { name: '', children: [] }
      newChild.showInput = true
      newChild.remove = true
      this.deptOptions.unshift(newChild)
    },
    // 确定添加树节点
    sureNode(node, data) {
      this.appendState = false
      if (data.itemLabel) {
        if (data?.id) {
          editTemplateType({ itemLabel: data.itemLabel, groupId: data.groupId, id: data.id }).then((res) => {
            this.$message.success('更新成功')
            this.getTreeselect()
            data.showInput = false
            data.remove = true
          })
        } else {
          addTemplateType({ label: data.itemLabel }).then((res) => {
            this.$message.success('新增成功')
            this.getTreeselect()
            data.showInput = false
            data.remove = true
          })
        }
      } else {
        this.$message.error('名称不能为空')
      }
    },
    // 重命名node
    editNode(node, data) {
      data.remove = false
      data.showInput = true
      data.oldItemLabel = data.itemLabel
    },
    // 移除树节点
    remove(node, data) {
      if (data.id) {
        data.remove = true
        data.showInput = false
        data.itemLabel = data.oldItemLabel
      } else {
        this.deptOptions.shift(data)
      }
    },
    //  删除节点
    delNode(node, data) {
      delTemplateType(data.id).then((res) => {
        this.$message.success('删除成功')
        this.getTreeselect()
      })
    },
    // 搜索框变化
    handleEvent(val) {
      const field = val.field
      const value = val.value
      this.queryParams = {
        ...this.queryParams,
        ...{
          [field]: value
        }
      }
    },
    /** 搜索 */
    handleQuery() {
      this.queryParams.current = 1
      this.queryParams.size = 10
      this.getDataList()
    },
    /** 查询列表 */
    getDataList(val) {
      this.loading = true
      this.queryParams = { ...this.queryParams, ...val, scrollToTop: true }
      this.queryParams.startTime = this.queryParams.reportTime && this.queryParams.reportTime[0]
      this.queryParams.endTime = this.queryParams.reportTime && this.queryParams.reportTime[1]

      queryPageList(this.queryParams).then((res) => {
        this.total = res.total
        this.tableDataList = res.list
        this.loading = false
        this.queryParams.scrollToTop = false
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      for (const key in this.queryParams) {
        this.queryParams[key] = undefined
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids
      this.$modal
        .confirm('是否确认删除所选数据项？')
        .then(function() {
          return deleteReport(id)
        })
        .then(() => {
          this.$modal.msgSuccess('删除成功')
          this.getDataList()
          this.getTreeselect()
        })
        .catch((error) => {
          console.log(error)
        })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      return new Promise((resolve, reject) => {
        getTemplateType().then((res) => {
          this.deptOptions = res.map((item) => {
            return {
              children: this.treeChild(item.children),
              itemLabel: item.itemLabel,
              id: item.id,
              groupId: item.groupId,
              itemVale: item.itemVale,
              showInput: false,
              remove: true,
              flag: item.flag
            }
          })
          resolve(this.deptOptions)
        })
      })
    },
    // 递归数据
    treeChild(item) {
      if (item) {
        return item.map((i) => {
          return {
            children: this.treeChild(i.children),
            dictKey: i.dictKey,
            id: i.id,
            showInput: false,
            remove: true,
            isLeaf: i.isLeaf
          }
        })
      } else return
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.itemLabel.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      return new Promise((resolve, reject) => {
        this.isHightlight = true
        this.queryParams.templateType = data.itemVale
        resolve(this.queryParams)
      }).then(() => {
        this.getDataList()
      })
    },
    // 右侧新增完成
    handleSubmit() {
      this.getDataList()
      this.getTreeselect()
      this.dialogFlag = false
    },
    /** 新增按钮操作 */
    async handleAdd() {
      // this.title = '添加'
      await this.setDialogTitle('添加')
      this.$refs.editRef.show()
      this.$refs.editRef.cycle = 'month'
      this.$refs.editRef.changeTime('month')
    },

    /** 关联配置 */
    async handleRelevance(row) {
      // this.title = '关联配置'
      await this.setDialogTitle('关联配置')
      this.$refs.editRef.configId = row.configId
      this.$refs.editRef.show()
    },

    /** 解决异步问题 */
    async setDialogTitle(name) {
      this.title = name
    },

    /** 操作 */
    handleCommand(command, row) {
      const url = `/dispose-api/report/download${row.filePath}.${command}`
      if (command === 'wps') {
        this.downloadByUrl(url, row.reportName + '.wps')
      } else {
        this.downloadByUrl(url, row.reportName, command)
      }
    },

    /** 预览 */
    handlePreview(row) {
      window.open(`/dispose-api/report/download${row.filePath}.html`)
    },

    /** 下载 */
    downloadByUrl(src, filename, suffix) {
      const x = new XMLHttpRequest()
      x.open('GET', src, true)
      x.responseType = 'blob'
      x.onload = function(e) {
        const userAgent = navigator.userAgent // 取得浏览器的userAgent字符串
        const url = window.URL.createObjectURL(x.response)
        if (userAgent.indexOf('Firefox') > -1) {
          const link = document.createElement('a')
          const body = document.querySelector('body')
          link.href = window.URL.createObjectURL(x.response)
          if (suffix == 'pdf') {
            link.download = filename + '.pdf'
          } else if (suffix == 'doc') {
            link.download = filename + '.doc'
          } else {
            link.download = filename
          }

          link.style.display = 'none'
          body.appendChild(link)

          link.click()
          body.removeChild(link)
          window.URL.revokeObjectURL(link.href)
        } else {
          const a = document.createElement('a')
          a.href = url
          a.target = '_blank'
          a.download = filename
          a.click()
          a.remove()
        }
      }
      x.send()
    }
  }
}
</script>
<style lang="scss" scoped>
.el-button + .el-button {
  margin-left: 0px;
}
::v-deep .el-icon-circle-plus {
  font-size: 16px !important;
}
.app-container {
  padding: 0;
}
.msg-title {
  padding-bottom: 10px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
.user {
  padding: 20px;
  width: calc(100% - 270px);
  height: 100%;
  display: flex;
  flex-direction: column;
}
.full-row {
  width: 100%;
  display: flex;
  margin: 0 !important;
  height: 100%;

  .full-height {
    height: 100%;
    display: flex;
    width: 270px;
    flex-direction: column;
    border-right: 1px solid rgba(0, 0, 0, 0.08);
    .head-container {
      margin-top: 10px;
      overflow-x:hidden !important;
      .title {
        cursor: pointer;
        font-size: 14px;
        padding: 5px 10px !important;
        background: #f8f8f8;
        .tit-left {
          flex: 1;
          span {
            margin-left: 10px;
          }
        }
      }
    }
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    overflow: hidden !important;
  }
}
.innerput::v-deep input {
  width: 100px;
  font-size: 14px;
  padding: 0 5px;
}
::v-deep {
  .el-input-group--append {
    width: 100%;
    input {
      border-right: none;
    }
    .el-input__inner:hover {
      border-color: #c0c4cc !important ;
    }
  }
  .el-input-group__append {
    background-color: transparent;
    border-left: none;
  }
}
</style>
<style lang="scss" scoped>
.dictMapping {
  width: 100%;
  height: 100%;
  .el-tree {
    margin-top: 10px;
    font-size: 14px;
  }
}
</style>
